{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "wav_path='/Users/leizhen/Documents/文档/供应链总文件夹/物流系统总文件夹/物流系统升级/物流系统升级会议录音资料/distvocie.wav'\n",
    "import os\n",
    "if os.path.exists('./segdir')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 音频分割\n",
    "import wave\n",
    "seg=1000000\n",
    "with wave.open(wav_path,'rb') as f:\n",
    "    print(f.getparams())\n",
    "    nframes=f.getnframes()\n",
    "    for i in range(nframes)[::seg]:\n",
    "        nframes=f.readframes(seg)\n",
    "        with wave.open('./segdir/seg{:0>3d}.wav'.format(int(i/seg)),'wb') as fw:\n",
    "            fw.setparams(f.getparams())\n",
    "            fw.writeframesraw(nframes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 获取所有的音频片段\n",
    "import glob\n",
    "segs=glob.glob('./segdir/*.wav')\n",
    "segs.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"access_token\":\"24.0994d2cdab294e3427a6f8b69f6196f4.2592000.1584637607.282335-18513174\",\"session_key\":\"9mzdCyF5lXgjmdLoXeCiNJirwdZ6Rx9kUQ4tQK6Bs2ts9lxpzU8vg3VCgsIug9to9rk4WFW6HIcXKNkpN\\/0wttEZ2MvwxQ==\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post public brain_all_scope picchain_test_picchain_api_scope wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406\",\"refresh_token\":\"25.d7abb301565facfa940225cd59eb03d7.315360000.1897405607.282335-18513174\",\"session_secret\":\"bb5c1276a10a5697f68789af53f0b2ab\",\"expires_in\":2592000}\n",
      "\n",
      "{'access_token': '24.0994d2cdab294e3427a6f8b69f6196f4.2592000.1584637607.282335-18513174', 'session_key': '9mzdCyF5lXgjmdLoXeCiNJirwdZ6Rx9kUQ4tQK6Bs2ts9lxpzU8vg3VCgsIug9to9rk4WFW6HIcXKNkpN/0wttEZ2MvwxQ==', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post public brain_all_scope picchain_test_picchain_api_scope wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理', 'refresh_token': '25.d7abb301565facfa940225cd59eb03d7.315360000.1897405607.282335-18513174', 'session_secret': 'bb5c1276a10a5697f68789af53f0b2ab', 'expires_in': 2592000}\n",
      "audio_voice_assistant_get\n",
      "SUCCESS WITH TOKEN: 24.0994d2cdab294e3427a6f8b69f6196f4.2592000.1584637607.282335-18513174  EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 5.962699\n",
      "{\"corpus_no\":\"6794834191471137442\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"这样子，这个要等哥要能够可以组合啊，因为怎么样也要看到就说在整体的人跟这个系统不光是服务于某一个值的公司？也不是服务某一个部门，然后整体的业务要发展成一下这么做，那第二个层面的，就是根据这三个不同的业务，业务形态啊就是这就是从我们本身的这个业务的，是这个形态，从快运经销商还有工业销售这个这个有三个右形状选选定一些呃，具有就是对标方向的，这个就是明确可以对标的一些企业啊通通过这个这个这个个子分公司的也都参与进来啊，尤其是我们专业的这个呃，领域比较强的时候是形成一些平衡的标准，那那如何去明确这些这些，或者说是怎么能够就是这个选定这些龙头企业就是我们行业的一个的那个杭州那个杭州那个杭州那个杭州那个杭州那个能够参照一些啊这些公司的这个业务的系统的集成啊不不不阔怕的这个？\"],\"sn\":\"408022608871582045618\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "# 访问百度api\n",
    "import sys\n",
    "import json\n",
    "import base64\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = 'RqNavKBpc4MFZ9L6QmuTpaSE'\n",
    "SECRET_KEY = '53Son82LGvqvvNgsag2Ru3K3XXSHiwum'\n",
    "\n",
    "# 需要识别的文件\n",
    "# AUDIO_FILE = segs  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:]  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON'\n",
    "# 采样率\n",
    "RATE = 16000  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537  # 1537 表示识别普通话，使用输入法模型。1536表示识别普通话，使用搜索模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "# DEV_PID = 80001\n",
    "# ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有极速版能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s  EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "#     循环获取\n",
    "    for index,AUDIO_FILE in enumerate(segs):\n",
    "        if index ==11:\n",
    "            time.sleep(10)\n",
    "            #断点重新开始的代码\n",
    "            speech_data = []\n",
    "            with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "                speech_data = speech_file.read()\n",
    "\n",
    "            length = len(speech_data)\n",
    "            if length == 0:\n",
    "                raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "            speech = base64.b64encode(speech_data)\n",
    "            if (IS_PY3):\n",
    "                speech = str(speech, 'utf-8')\n",
    "            params = {'dev_pid': DEV_PID,\n",
    "                     #\"lm_id\" : LM_ID,    #测试自训练平台开启此项\n",
    "                      'format': FORMAT,\n",
    "                      'rate': RATE,\n",
    "                      'token': token,\n",
    "                      'cuid': CUID,\n",
    "                      'channel': 1,\n",
    "                      'speech': speech,\n",
    "                      'len': length\n",
    "                      }\n",
    "            post_data = json.dumps(params, sort_keys=False)\n",
    "            # print post_data\n",
    "            req = Request(ASR_URL, post_data.encode('utf-8'))\n",
    "            req.add_header('Content-Type', 'application/json')\n",
    "            try:\n",
    "                begin = timer()\n",
    "                f = urlopen(req)\n",
    "                result_str = f.read()\n",
    "                print (\"Request time cost %f\" % (timer() - begin))\n",
    "            except URLError as err:\n",
    "                print('asr http response http code : ' + str(err.code))\n",
    "                result_str = err.read()\n",
    "\n",
    "            if (IS_PY3):\n",
    "                result_str = str(result_str, 'utf-8')\n",
    "            print(result_str)\n",
    "            with open(\"./result/result{:0>3d}.txt\".format(index),\"wt\") as of:\n",
    "                of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [],
   "source": [
    "#合并结果\n",
    "import glob\n",
    "results=glob.glob('./result/result*.txt')\n",
    "results.sort()\n",
    "import json\n",
    "text=''\n",
    "for result in results:\n",
    "    try:\n",
    "        with open(result,'rt') as f:\n",
    "            jobj=json.load(f)\n",
    "        text=text+jobj['result'][0]\n",
    "    except:\n",
    "        continue\n",
    "with open('alltext.txt','wt') as f:\n",
    "    f.write(text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<_io.TextIOWrapper name='./result/result011.txt' mode='rt' encoding='UTF-8'>"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
